package com.ss.zsensm;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import android.util.Log;

public class DataCollector implements Runnable {
	public static final int Stop = 0;
	public static final int Pending = 1;
	public static final int Running = 2;
	
	private MainActivity ui;
	private long sensitivity;
	private DatagramSocket sd;
	private InetAddress remoteAddr;
	private int playerId;
	private int status;
	
	public InetAddress getRemoteAddress() {
		return remoteAddr;
	}
	
	public boolean isStarted() {
		return status >= Pending;
	}
	
	public int getPlayerId() {
		return playerId;
	}
	
	public int getStatus() {
		return status;
	}
	
	// called by DataTransmission Thread(While DataTransmissionThread is not working)
	public void setRemote(InetAddress inetAddr, int playerId) {
		remoteAddr = inetAddr;
		this.playerId = playerId; 
		status = Pending;
	}
	
	public DataCollector(MainActivity mainActivity, long sensitivity) {
		ui = mainActivity;
		this.sensitivity = sensitivity;
		remoteAddr = null;
		status = Stop;
		playerId = 0;
		sd = null;
	}
	
	// called by DataTransmission Thread
	public void stop() {
		if (sd != null) {
			sd.close();
			sd = null;
		}
		status = Stop;
		// will be joined by other thread
	}
	
	// called by DataTransmission Thread
	public void pause() {
		if (sd != null) {
			sd.close();
			sd = null;
		}
		status = Pending;
		// will be joined by other thread
	}
	
	// called by DataCollector Thread
	@Override
	public void run() {
		status = Running;
		try {
			sd = new DatagramSocket();
		} catch (SocketException e) {
			Log.e("dc.run", e.toString());
		}
		Log.i("zsensm", "dc started");
		
		while (true) {
			if (status < Running)
				break;
			byte[] data = ui.getCollectedData();
			int hash = Serializing.hash(data, 5, data.length);
			Serializing.put(data, 1, hash);
			try {
				sd.send(new DatagramPacket(data, data.length, remoteAddr,
						PacketInfo.port));
			} catch (IOException e) {
				Log.e("zsensm", "dc.run.ioe: " + e.toString()); 
			} catch (NullPointerException npe) {
				Log.e("zsensm", "dt.run.npe: " + npe.getMessage());
			}
			try {
				Thread.sleep(this.sensitivity);
			} catch (InterruptedException e) {
				Log.e("zsensm", "dc.run.ie: " + e.getMessage());
			}
		}
	}
}
